<%@page import="entity.Admin"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  Admin admin = (Admin) session.getAttribute("admin");
  String deptName = "";
  if("部门".equals(admin.getIsSuper())) {
    deptName = admin.getDeptName();
  }
%>

<div class="callout callout-left">
  <span class="callout-title text-muted">用户管理</span><!-- &nbsp;<span class="glyphicon glyphicon-question-sign"></span> -->
  <a class="btn btn-primary" id="create_user" data-toggle="modal" href="#myModal" style="margin-left: 35px;"><span class="glyphicon glyphicon-plus-sign">&nbsp;新用户</span></a>
  <!-- <a class="btn btn-primary" data-toggle="modal" href="#mymodal"><span class="glyphicon glyphicon-import">&nbsp;导入用户</span></a> -->
</div>

<div class="callout">
  <form class="form-inline" method="post">
  <div class="form-group">
    <label for="userName_search">账号：</label>
    <input type="text" id="userName_search" name="userName_search" class="form-control"  placeholder="用户登陆账号" autocomplete="off" />
  </div>
  <div class="form-group">
    <label for="cnName_search">姓名：</label>
    <input type="text" id="cnName_search" name="cnName_search" class="form-control"  placeholder="用户真实姓名" autocomplete="off" />
  </div>
  <div class="form-group">
    <label for="category_search">身份类型：</label>
    <select class="form-control" id="category_search" name="category_search">
      <option value="">--请选择--</option>
    </select>
  </div>
  <div class="form-group">
    <label for="status_search">状态：</label>
    <select class="form-control" id="status_search" name="status_search">
      <option value="">--请选择--</option>
      <option value="正常">正常</option>
      <option calue="注册">注册</option>
      <option calue="禁用">禁用</option>
    </select>
  </div>&nbsp;&nbsp;&nbsp;
  <div class="form-group">
    <label for="start_search">开始日期：</label>
    <div class='input-group'>
      <input type='text' class='form-control' id='start_search' name='start_search' placeholder='开始日期'/>
      <span class='glyphicon glyphicon-calendar input-group-addon' style='top: 0;'></span>
    </div>
  </div>
  <div class="form-group">
    <label for="end_search">结束日期：</label>
    <div class='input-group'>
      <input type='text' class='form-control' id='end_search' name='start_search' placeholder='结束日期'/>
      <span class='glyphicon glyphicon-calendar input-group-addon' style='top: 0;'></span>
    </div>
  </div>
  <button type="button" class="btn btn-primary" id="doSearch">
    <span class="glyphicon glyphicon-search">&nbsp;搜索</span>
  </button>
</form>
</div>

<div class="callout">
  <div class="text-muted" style="display:inline-block;">批量操作：<span id='approve_amount'>0</span>条</div>&nbsp;&nbsp;
  <a href="javascript:;" id="batch_approve" class="btn btn-info"><span class="glyphicon glyphicon-ok">&nbsp;审批</span></a>
</div>

<div class="callout callout-white">
  <div class="table-responsive">
    <table class="table table-hover">
      <thead>
        <tr>
          <th><label class="checkbox-inline"><input type="checkbox" id="th_row"/>编号</label></th>
          <th>登陆账号</th>
          <th>邮箱</th>
          <th>姓名</th>
          <th>身份类型</th>
          <th>所属部门</th>
          <th>登陆次数</th>
          <th>激活次数</th>
          <th>请求次数</th>
          <th>注册时间</th>
          <th>状态</th>
          <th>动作</th>
        </tr>
      </thead>
      <tbody id="users_content">
      </tbody>
    </table>
  </div>
</div>

<script>
require.config({
  baseUrl: '<%=path %>/js',
  paths: {
    jquery: 'jquery-1.9.1.min',
    commmon: 'common',
    bootstrapswitch: 'bootstrap-switch.min',
    md5: 'md5'
  }
});

require(['jquery', 'common', 'md5', 'bootstrapswitch'], function($, common, md5) {
//console.log("用户管理模块载入");

var workspace = function() {
  var domKey;
  var dataOpt;

  var departments;
  var categorys;
  var users;

  var init = function() {
      dataOpt = common.dataOpt;
      domKey = common.commData.domKey;

      departments = common.ajaxLoadData(dataOpt.departmentOpt);
      categorys = common.ajaxLoadData(dataOpt.categoryOpt);
      dataOpt.userOpt.data = {"deptName":encodeURI(encodeURI("<%=deptName %>"))}

      _datePiclerInit();
      _setSearchDate();
      _initUsersTable();
      _createUser();
      _searchUser();
  }

  var _setSearchDate = function() {
    var startDate = $("#start_search").val();
    var endDate = $("#end_search").val();

    if(startDate === endDate) {
       var addDate = new Date(endDate);
       addDate.setDate(addDate.getDate() + 1);
       endDate = addDate.Format("yyyy-MM-dd");
    }
    dataOpt.userOpt.data = {
       "startDate": encodeURI(encodeURI(startDate)),
       "endDate": encodeURI(encodeURI(endDate))
    }
  }

  var _datePiclerInit = function() {
  var now = new Date();
  var sevenBefore = new Date(new Date().setDate(now.getDate() - 7));

  $("#end_search").val(now.Format("yyyy-MM-dd"))
  $("#start_search").val(sevenBefore.Format("yyyy-MM-dd"));

  common.datePickerInit($("#end_search"));
  common.datePickerInit($("#start_search"));
}

  // 状态切换按钮
  var initSwitch = function() {
    $(".bootstrap-switch").each(function() {
       var f;
       var $st = $(this).parent().find("[name='status_text']");
       if($st.html() !== "注册") {
          $(this).removeClass("hidden").find(":input:checkbox").bootstrapSwitch({
             animate: true,
             handleWidth: "5px",
             onText: "&nbsp;&nbsp;&nbsp;&nbsp;",
             offText: "&nbsp;&nbsp;&nbsp;&nbsp;",
             onInit: function() {// 按钮初始化动作
                if("正常" === $st.html()) {
                    $st.removeClass("text-danger").addClass("text-success");
                    f = true;
                } else {
                    $st.removeClass("text-success").addClass("text-danger");
                    f = false;
                }
             },
             onSwitchChange: function(e, state) {
                var name = $(this).data("name");
                if(true === state) {// 启用
                    $st.removeClass("text-danger").addClass("text-success").html("正常");
                    common.switchStatusAjax("users", "正常", name);
                } else {// 禁用
                    $st.removeClass("text-success").addClass("text-danger").html("禁用");
                    common.switchStatusAjax("users", "禁用", name);
                }
             }
          });
          $(this).find(":checkbox").bootstrapSwitch('state', f);
        }
    });
  }

  // 分页
  var pageNav = function(htmlArr) {
      var opt = {
          htmlArr: htmlArr,
          content: $("#users_content"),
          // curPage: curPage
      }
      common.pageNav(opt, function() {
          // 状态颜色
          $("[name='status_text']").each(function() {
              if("正常" == $(this).html()) {
                  $(this).addClass("text-success");
              } else if("禁用" == $(this).html()) {
                  $(this).addClass("text-danger");
              } else {// 注册
                  $(this).addClass("text-warning");
              }
          });

          initSwitch();
          editUser();
          delUser();
          approveUser();
          batchApprove();
      });
  }

  // 初始化表格
  var _initUsersTable = function() {
      users = common.ajaxLoadData(dataOpt.userOpt);
      dataOpt.userOpt.data = { "deptName":encodeURI(encodeURI("<%=deptName %>")) }

    var template = "<tr>" +
      "<th scope='row'><label class='checkbox-inline'><input type='checkbox' name='user_#row#' value='#userName#' />#row#</label></th>" +
      "<td>#userName#</td>" +
      "<td>#email#</td>" +
      "<td>#cnName#</td>" +
      "<td>#category#</td>" +
      "<td>#deptName#</td>" +
      "<td>#loginTimes#</td>" +
      "<td>#actTimes#</td>" +
      "<td>#requestTimes#</td>" +
      "<td>#regTime#</td>" +
      "<td>" +
      "<div class='bootstrap-switch bootstrap-switch-mini hidden' style='top: -1px;'><input type='checkbox' checked data-name='#userName#' /></div>" +
      "&nbsp;<span name='status_text'>#status#</span>" +
      "</td>" +
      "<td class='text-primary'>" +
      "<a href='javascript:;' class='approve' data-name='#userName#' data-status='#status#'><span class='glyphicon glyphicon-ok'>审批</span></a>&nbsp;&nbsp;" +
      "<a href='#myModal' class='editUser' data-toggle='modal' data-name='#userName#'><span class='glyphicon glyphicon-edit'>编辑</span></a>&nbsp;&nbsp;" +
      "<a href='#myModal' class='delUser' data-toggle='modal' data-name='#userName#'><span class='glyphicon glyphicon-remove'>删除</span></a>" +
      "</td></tr>";

      var row = 0;
      var htmlArr = [];
		  var html = [];
      var thisT = "";
      for(var i = 0, n = users.length; i < n; i++ ) {
        thisT = template;
        thisT = thisT.replace(/#row#/g, ++row).replace(/#userName#/g, users[i]["userName"]).replace(/#category#/g, users[i]["category"]).replace(/#deptName#/g, users[i]["deptName"])
          .replace(/#status#/g, users[i]["status"]).replace(/#loginTimes#/g, users[i]["loginTimes"]).replace(/#regTime#/g, users[i]["regTime"]).replace(/#email#/g, users[i]["email"])
          .replace(/#actTimes#/g, users[i]["actTimes"]).replace(/#requestTimes#/g, users[i]["requestTimes"]).replace(/#cnName#/g, users[i]["cnName"]);
        html += thisT;
          if((row !== 0) && (row % common.commData.pageNum === 0)) {
              htmlArr.push(html);
              html = "";
          }
      }
      if("" !== html) {
          htmlArr.push(html);// 插入不满pageNum的几条数据
      }
      $("#users_content").html(htmlArr[0]);

      pageNav(htmlArr);
  }

  // 创建用户
  var _createUser = function() {
      var modalBodyTemplate = "<form class='form-horizontal'>" +
          "<div class='form-group'>" +
          "<label for=userName class='col-sm-3 control-label'>登陆账号</label>" +
          "<div class=col-sm-9>" +
          "<input type='text' class='form-control' id='userName' name='userName' placeholder='登陆账号' autocomplete='off' />" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='category' class='col-sm-3 control-label'>身份类型</label>" +
          "<div class='col-sm-9'>" +
          "<select class='form-control' name='category' id='category'>" +
          // "<option value=''>1c</option>" +
          "</select></div></div>" +
          "<div class='form-group'>" +
          "<label for='cnName' class='col-sm-3 control-label'>姓名</label>" +
          "<div class='col-sm-9'>" +
          "<input type='text' class='form-control' id='cnName' name='cnName' placeholder='真实姓名' autocomplete='off' />" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='email' class='col-sm-3 control-label'>邮箱</label>" +
          "<div class='col-sm-9'>" +
          "<input type='text' class='form-control' id='email' name='email' placeholder='电子邮箱' autocomplete='off' />" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='password' class='col-sm-3 control-label'>登录密码</label>" +
          "<div class='col-sm-9'>" +
          "<input type='text' class='form-control' id='password' name='password' placeholder='登录密码' autocomplete='off' />" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='deptName' class='col-sm-3 control-label'>所属部门</label>" +
          "<div class='col-sm-9'>" +
          "<select class='form-control' name='deptName' id='deptName'>" +
          // "<option value=''>1c</option>" +
          "</select></div></div>" +
          "<div class='form-group'>" +
          "<label for='status' class='col-sm-3 control-label'>状态</label>" +
          "<div class='col-sm-9'>" +
          "<select class='form-control' name='status' id='status'>" +
          "<option value='正常'>正常</option>" +
          "<option value='禁用'>禁用</option>" +
          "</select></div></div></form>";

      $("#create_user").click(function() {
          common.cleanModal();
          domKey.modalLabel.html("新建用户");
          domKey.modalBody.html(modalBodyTemplate);

          // 身份类型
          for(var i = 0, n = categorys.length; i < n; i++) {
              var opt = document.createElement("option");
              $(opt).val(categorys[i]);
              $(opt).text(categorys[i]);
              $("#category").append(opt);
          }

          // 部门
          for(var i = 0, n = departments.length; i < n; i++) {
              var opt = document.createElement("option");
              $(opt).val(departments[i]["deptName"]);
              $(opt).text(departments[i]["deptName"]);
              $("#deptName").append(opt);
          }

          domKey.modalAct.html("新建")
          .on("click", function() {
              common.disable(domKey.modalAct);// 提交请求则禁掉按钮
              var data = {
                  "cnName": $("#cnName").val(),
                  "category": $("#category option:selected").val(),
                  "userName": $("#userName").val(),
                  "email": $("#email").val(),
                  "password": md5($("#password").val()),
                  "deptName": $("#deptName option:selected").val(),
                  "status": $("#status option:selected").val(),
                  "adminName": "<%=admin.getAdminName() %>"
              }

              if(data["cnName"].length === 0 || data["userName"].length === 0 || data["email"].length === 0 || data["password"].length === 0) {
                  swal("提示", "请填写所有信息", "warning");
                  common.enable(domKey.modalAct);
              } else if(!common.isName(data["userName"])) {
                  swal("提示", "用户名只能包含字母、数字和下划线的字符", "warning");
                  common.enable(domKey.modalAct);
              } else if(!common.isPasswd($("#password").val())) {
                  swal("提示", "密码只能6-20个包含字母、数字和下划线的字符", "warning");
                  common.enable(domKey.modalAct);
              } else {
                  $.ajax({
                      url: "<%=path %>/servlet/user/CreateUserServlet",
                      type: "post",
                      data: data,
                      dataType: "json",
                      async: false,
                      success: function(json) {
                          if("1" == json["retCode"]) {

                          } else {
                              alert(json["desc"]);
                          }
                      },
                      error: function(XMLHttpRequest, textStatus, errorThrown) {
                          alert("CreateUserServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
                      },
                      complete: function() {
                          domKey.modal.find(".close").click();
                          _initUsersTable();// 刷新表格
                      }
                  });
              }
          });
      });
  }
	
  // 编辑用户
  var editUser = function() {
      var modalBodyTemplate = "<form class='form-horizontal'>" +
          "<div class='form-group'>" +
          "<label for=userName class='col-sm-3 control-label'>登陆账号</label>" +
          "<div class=col-sm-9>" +
          "<input type='text' class='form-control' id='userName' name='userName' placeholder='登陆账号' autocomplete='off' readonly/>" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='category' class='col-sm-3 control-label'>身份类型</label>" +
          "<div class='col-sm-9'>" +
          "<select class='form-control' name='category' id='category'>" +
          // "<option value=''>1c</option>" +
          "</select></div></div>" +
          "<div class='form-group'>" +
          "<label for='cnName' class='col-sm-3 control-label'>姓名</label>" +
          "<div class='col-sm-9'>" +
          "<input type='text' class='form-control' id='cnName'  name='cnName'  placeholder='真实姓名' autocomplete='off' />" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='email' class='col-sm-3 control-label'>邮箱</label>" +
          "<div class='col-sm-9'>" +
          "<input type='text' class='form-control' id='email' name='email' placeholder='电子邮箱'  autocomplete='off' />" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='password' class='col-sm-3 control-label'>登陆密码</label>" +
          "<div class='col-sm-9'>" +
          "<label class='checkbox-inline'><input type='checkbox' id='password' name='password' />重置（初始密码：123qwe）</label>" +
          "</div></div>" +
          "<div class='form-group'>" +
          "<label for='deptName' class='col-sm-3 control-label'>所属部门</label>" +
          "<div class='col-sm-9'>" +
          "<select class='form-control' name='deptName' id='deptName'>" +
          // "<option value=''>1c</option>" +
          "</select></div></div>" +
//			"<div class='form-group'>" +
//			"<label for='status' class='col-sm-3 control-label'>状态</label>" +
//			"<div class='col-sm-9'>" +
//			"<select class='form-control' name='status' id='status'>" +
//			"<option value='正常'>正常</option>" +
//			"<option value='禁用'>禁用</option>" +
//			"</select></div></div>" +
          "<input type='hidden' id='password_hide' value=''/></form>";

      $(".editUser").each(function() {
          var userName = $(this).data("name");
          $(this).click(function() {
              common.cleanModal();
              domKey.modalLabel.html("编辑用户");
              domKey.modalBody.html(modalBodyTemplate);

              // 身份类型
              for(var i = 0, n = categorys.length; i < n; i++) {
                  var opt = document.createElement("option");
                  $(opt).val(categorys[i]);
                  $(opt).text(categorys[i]);
                  $("#category").append(opt);
              }

              // 部门
              for(var i = 0, n = departments.length; i < n; i++) {
                  var opt = document.createElement("option");
                  $(opt).val(departments[i]["deptName"]);
                  $(opt).text(departments[i]["deptName"]);
                  $("#deptName").append(opt);
              }

              showUserData(userName);

              domKey.modalAct.html("保存")
              .on("click", function() {
                  common.disable(domKey.modalAct);// 提交请求则禁掉按钮
                  var data = {
                      "cnName": $("#cnName").val(),
                      "category": $("#category option:selected").val(),
                      "userName": $("#userName").val(),
                      "email": $("#email").val(),
                      "password": $("#password").is(":checked") ? md5("123qwe") : $("#password_hide").val(),
                      "deptName": $("#deptName option:selected").val(),
                      // "status": $("#status option:selected").val(),
                      "adminName": "<%=admin.getAdminName() %>"
                  }
                  if(data["cnName"].length === 0 || data["userName"].length === 0 || data["email"].length === 0) {
                      swal("请填写所有信息", "", "warning");
                      common.enable(domKey.modalAct);
                  } else {
                      $.ajax({
                          url: "<%=path %>/servlet/user/EditUserServlet",
                          type: "post",
                          data: data,
                          dataType: "json",
                          async: false,
                          success: function(json) {
                              if("1" == json["retCode"]) {

                              } else {
                                  alert(json["desc"]);
                              }
                          },
                          error: function(XMLHttpRequest, textStatus, errorThrown) {
                              alert("EditUserServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
                          },
                          complete: function() {
                              domKey.modal.find(".close").click();
                              _initUsersTable();// 刷新表格
                          }
                      });
                  }
              });
          });
      });

      // 渲染修改数据
      var showUserData = function(uname) {
          for(var i = 0, n = users.length; i < n; i++) {
              if(users[i]["userName"] == uname) {
                  $("#cnName").val(users[i]["cnName"]);
                  $("#category").val(users[i]["category"]);
                  $("#password_hide").val(users[i]["password"]);
                  $("#userName").val(users[i]["userName"]);
                  $("#email").val(users[i]["email"]);
                  $("#deptName").val(users[i]["deptName"]);
                  $("#status").val(users[i]["status"]);
                  break;
              }
          }
      }
  }

  // 删除管理员
  var delUser = function() {
      var modalBodyTemplate = "<span class='glyphicon glyphicon-info-sign' style='color:#FF8A00;font-size:26px;margin-right:15px;top:7px;'></span>确认删除#name#？";
      $(".delUser").each(function() {
          var userName = $(this).data("name");
          $(this).on("click", function() {
              common.cleanModal();
              domKey.modal.find(".modal-dialog").addClass("modal-sm");
              var thisTemplate = modalBodyTemplate;
              thisTemplate = thisTemplate.replace(/#name#/g, userName);
              domKey.modalLabel.html("删除用户");
              domKey.modalBody.html(thisTemplate);

              domKey.modalAct.html("确认")
              .on("click", function() {
                  common.disable(domKey.modalAct);// 提交请求则禁掉按钮
                  $.ajax({
                      url: "<%=path %>/servlet/user/DelUserServlet",
                      type: "post",
                      data: {"userName": userName},
                      dataType: "json",
                      async: false,
                      success: function(json) {
                          if("1" == json["retCode"]) {
                              // console.log("删除管理员成功");
                          } else {
                              alert(json["desc"]);
                          }
                      },
                      error: function(XMLHttpRequest, textStatus, errorThrown) {
                          alert("DelUserServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
                      },
                      complete: function() {
                          domKey.modal.find(".close").click();
                          _initUsersTable();// 刷新表格
                      }
                  });
              });
          });
      });
  }

  // 审批用户
  var approveUser = function() {
      $(".approve").each(function() {
          var status = $(this).data("status");
          var userName = $(this).data("name");
          if("正常" == status || "禁用" == status) {
              $(this).addClass("a-disabled");
          } else {// 注册状态下才有审批动作
              $(this).click(function() {
                  common.approveUser(userName);
                  _setSearchDate();
                  _initUsersTable();
              });
          }
      });
  }

  // 批量审批
  var batchApprove = function() {
      // 全选反选操作
      $("#th_row").change(function() {
          var isChecked = $(this).prop("checked");
          $(":checkbox[name^='user_']").each(function() {
              $(this).prop("checked", isChecked);
          });
          $("#approve_amount").html($(":checkbox[name^='user_']:checked").length);
      });

      $(":checkbox[name^='user_']").change(function() {
          $("#approve_amount").html($(":checkbox[name^='user_']:checked").length);
      });

      // 审批操作
      $("#batch_approve").click(function() {
          $(":checkbox[name^='user_']:checked").each(function() {
              common.approveUser($(this).val());
          });
          _setSearchDate();
          _initUsersTable();
      });
  }

  // 搜索用户
  var _searchUser = function() {
      // 身份类型
      var searchCategory = function() {
          var opt;
          for(var i = 0, n = categorys.length; i < n; i++) {
              opt = document.createElement("option");
              $(opt).val(categorys[i]);
              $(opt).text(categorys[i]);
              $("#category_search").append(opt);
          }
      }();



      $("#doSearch").click(function() {
    var startDate = $("#start_search").val();
    var endDate = $("#end_search").val();

    if(startDate === endDate) {
      var addDate = new Date(endDate);
      addDate.setDate(addDate.getDate() + 1);
      endDate = addDate.Format("yyyy-MM-dd");
    }
          common.commData.curPage = 0;
          var data = {
              "userName": encodeURI(encodeURI($("#userName_search").val())),
              "cnName": encodeURI(encodeURI($("#cnName_search").val())),
              "category": encodeURI(encodeURI($("#category_search").val())),
              "status": encodeURI(encodeURI($("#status_search").val())),
      "startDate": encodeURI(encodeURI(startDate)),
      "endDate": encodeURI(encodeURI(endDate))
          }
          $.extend(true, dataOpt.userOpt.data, data);
          _initUsersTable();
      });
  }

  return {
      init: init
  }
}();
	
	
$(function() { workspace.init(); });

});
requirejs.onError = function (err) {  
  console.error(err);
  if (err.requireType === 'timeout') {
      console.error('modules: ' + err.requireModules);
  }
  throw err;
}
</script>